<template>
  <div class="book-selector">
    <div v-if="isShowReSelect">
      <span>{{ value }}</span>
      <Button type="dashed" size="small" style="margin-left: 10px" @click="handleReSelect">重新选择</Button>
    </div>
    <AutoComplete
      v-else
      v-model="bookid"
      :data="datas"
      icon="ios-search"
      @on-search="handleSearch"
      placeholder="试试输入书籍名称"
      style="width:300px"
    >
      <div
        v-for="(item, index) in datas2"
        :key="index"
        class="book-selector-item"
        @click="handleSelect(item)"
      >
        <span>{{ item.name }}</span>
      </div>
    </AutoComplete>
  </div>
</template>

<script>
import debounce from '@/utils/debounce';
import http from '@/utils/http';

const doSearch = debounce(
  (value, self) => {
    http({
      method: 'GET',
      url: '/api/admin/book/search',
      params: { keyword: value },
      operation: '搜索书籍'
    }).then(res => {
      if (res && res.ok) {
        self.datas = res.data.list.map(item => item.name);
        self.datas2 = res.data.list;
      }
    });
  },
  300,
  true
);

export default {
  name: 'm-book-selector',

  props: {
    value: String
  },

  data () {
    return {
      bookid: '',
      datas: [],
      datas2: []
    };
  },

  computed: {
    isShowReSelect () {
      return this.datas.length === 0 && this.value;
    }
  },

  methods: {
    handleSearch (value) {
      doSearch(value, this);
    },

    handleSelect (item) {
      this.bookid = item.name;
      this.$emit('update:value', item._id);
    },

    handleReSelect () {
      this.bookid = '';
      this.$emit('update:value', '');
    }
  }
};
</script>

<style lang="scss">
.book-selector-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;

  &:active {
    background: #fefefe;
  }

  & > span {
    display: inline-block;
    width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .ivu-select-dropdown-list {
    max-height: 300px;
    overflow: auto;
  }
}
</style>
